function wav_analysis
%filename = '.\WEB\DATA\WAV\AMOTE_1284037885712.amr.wav';
%filename = '.\WEB_2s@4s_sig390D1@16s\DATA\WAV\AMOTE_1284290392880.amr.wav';
%filename = '.\WEB\DATA\WAV\AMOTE_1283961424218.amr.wav';
%filename = 'dig11bits@100ms_4times_520D20.wav';
%filename = '.\WEB\DATA\WAV\MOTE-94_1285328168084.amr.wav';

%filename = '.\WEB\DATA\WAV\BMOTE-50_1285327645806.amr.wav';

%decode_single_frequency_wav(filename)

%filename='bmote50.wav';

%filename = '.\WEB\DATA\WAV\MOTE-94_1286278762947.amr.wav';
filename = '10min_1+6@200ms_500+2u.wav';

%filename='..\endoding_wav\dig11bits@100ms_520D20.wav';
%decode_single_freq_message(filename);
%decode_amplitude_message(filename);
decode_single_frequency_wav(filename);
%1284038056268
%freq = obtain_main_frequency(filename)
%components = obtain_wav_frequency_components(filename);

% [y, Fs, nbits] = wavread(filename);
% decodeBinary(y, Fs)
% return


% for i=1:size(components,1)
%     disp(['Peak:' num2str(components(i,2)) ' ' num2str(components(i,1)) ' Hz']);
% end
% ordered = order_frequency_components(components);
% for i=1:size(ordered,1)
%     disp(['>>Peak:' num2str(ordered(i,2)) ' ' num2str(ordered(i,1)) ' Hz']);
% end

%% Generate a signal

% % Fs = 10000;                    % Sampling frequency
% % T = 1/Fs;                     % Sample time
% % L = 10000;                     % Length of signal
% % t = (0:L-1)*T;                % Time vector
% % % Sum of a 500 Hz sinusoid and a 1200 Hz sinusoid
% % x = 0.7*sin(2*pi*500*t) + sin(2*pi*1200*t); 
% % y = x + 2*randn(size(t));     % Sinusoids plus noise
% % %y = 0.1*y;


% % Fs = 1000;                    % Sampling frequency
% % T = 1/Fs;                     % Sample time
% % L = 1000;                     % Length of signal
% % t = (0:L-1)*T;                % Time vector
% % % Sum of a 50 Hz sinusoid and a 120 Hz sinusoid
% % x = 0.7*sin(2*pi*50*t) + sin(2*pi*120*t); 
% % y = x + 2*randn(size(t));     % Sinusoids plus noise

% % plot(Fs*t,y)
% % 
% % % Save to file
% % wavwrite(y,filename)

%% Read a wav file

% % % wav information
% % %[m d] = wavfinfo(filename);
% % 
% % % read wav file
% % % sample rate (Fs) in Hertz 
% % %number of bits per sample (nbits) used to encode the data in the file.
% % [y, Fs, nbits] = wavread(filename);
% % 
% % %Fs = 1000;          % Sampling frequency
% % T = 1/Fs;           % Sample time
% % L = length(y);           % Length of signal
% % t = (0:L-1)*T;      % Time vector
% % 
% % %total_time = L * T
% % %plot(Fs*t,y)

%% Calculate fft
% % 
% % NFFT = 2^nextpow2(L); % Next power of 2 from length of y
% % Y = fft(y,NFFT)/L;
% % f = Fs/2*linspace(0,1,NFFT/2);
% % 
% % h = figure('Name', 'Multiple graph');
% % hold on
% % subplot(3,1,1)
% % plot(y)
% % subplot(3,1,2)
% % plot(Fs*t,y)
% % 
% % subplot(3,1,3)
% % % Plot single-sided amplitude spectrum.
% % plot(f,2*abs(Y(1:NFFT/2)))
% % 
% % % Main frequency is the position of the max value.
% % [val,pos]=max(abs(Y(1:NFFT/2)));
% % peak_freq = round(f(pos));
% % fixed_freq = round(peak_freq / 0.96); %experimental shift correction
% % 
% % title(strcat('Single-Sided Amplitude Spectrum of y(t), PEAK=', num2str(peak_freq), '->', num2str(fixed_freq)  ));
% % xlabel('Frequency (Hz)')
% % ylabel('|Y(f)|')
% % 
% % Npoints = 400;
% % Ny = y(round(L/2)+1:round(L/2)+Npoints);
% % 
% % plot_ffts(Ny, 6, Fs);
% % 

%% Multiple FFTs

% % L = length(y);
% % slot_duration = 0.5; % seconds
% % total_time = L/Fs;
% % slot_duration = floor(10*total_time/5)/10;
% % NSlots = floor(total_time/slot_duration);
% % points_per_slot = floor(L/NSlots);
% % disp ( ['Points per slot: ' num2str(points_per_slot) ] );
% % index = 1;
% % freqs = [];
% % %for i=1:3
% % for i=1:NSlots
% %     y_slot = y(index:index + points_per_slot-1); 
% %     components = calculateFFT(y_slot,Fs,1);
% %     freqs = [ freqs components(1)];
% %     disp( ['Main freq: ' num2str(components(1)) ] );
% %     index = index + points_per_slot;
% % end
% % %freq = mode(freqs);
% % freq = get_most_frequent(freqs);
% % %freq_std = std(freqs);
% % disp( ['Most freq: ' num2str(freq) ] );

%% Digital decoding
% [y, Fs, nbits] = wavread(filename);
% 
% h = figure('Name', 'Slots');
% hold on
% timming = 1;
% for i=1:5
%     components = 300*i + digital_decoding(y,Fs,timming);
%     color = get_a_new_color();
%     plot(components,'-ob', 'color',color);
% end
% 
% 
end
 

% % function components = calculateFFT(y,Fs)
% % 
% % T = 1/Fs;           % Sample time
% % L = length(y);      % Length of signal
% % t = (0:L-1)*T;      % Time vector
% % total_time = L * T;
% % 
% % %% Calculate fft
% % NFFT = 2^nextpow2(L); % Next power of 2 from length of y
% % Y = fft(y,NFFT)/L;
% % f = Fs/2*linspace(0,1,NFFT/2);
% % 
% % % Main frequency is the position of the max value.
% % [val,pos]=max(abs(Y(1:NFFT/2)));
% % peak_freq = round(f(pos));
% % 
% % components = peak_freq;
% % end
% % 

function value=get_most_frequent(values)
%Obtain the mode of the values/100
mode_value = mode(round(values/100))*100;

% Obtain the main value of the points closer to the mode
counter = 0;
suma = 0;
for i=1:length(values)
    value = values(i);
    if ( abs(value-mode_value) < 100 )
        suma = suma + value;
        counter= counter+1;
    end
end
if (counter<1)
    value = 0;
    return;
end
value = suma/counter;
end

function plot_ffts(y, number, Fs)

L = length(y);

h = figure('Name', 'Multiple FFTs');
hold on

for i=1:1:number
    NFFT = 2^ (6+i); %NFFT = 2^nextpow2(L);
    Y = fft(y,NFFT)/L;
    f = Fs/2*linspace(0,1,NFFT/2);

    [val,pos]=max(abs(Y(1:NFFT/2)));
    peak_freq = round(f(pos));

    subplot(number,1,i)
	plot(f,2*abs(Y(1:NFFT/2)))
    title(strcat('FFT N=', num2str(NFFT),' PEAK=', num2str(peak_freq) ));
end

end

%% FUNCTIONS

function ordered = order_frequency_components(components)
% max amplitude
[val,pos]=max(components(:,2));
max_amp_pos = pos;
max_amp = val;
max_amp_freq = components(pos,1);

significant_pos = -1;

for i=1:size(components,1)
    f = components(i,1);
    rel_amplitude = components(i,2)/max_amp;
    if ( f < max_amp_freq && rel_amplitude > 0.5)
        significant_pos = i;
        break;
    end
end    

%if exists a lower freq significant peak
if (significant_pos > 0) 
    ordered = [components(significant_pos,1) components(significant_pos,2) ];
    ordered = [ordered; components(max_amp_pos,1) components(max_amp_pos,2) ];
else
    ordered = [components(max_amp_pos,1) components(max_amp_pos,2) ];
end

%append the remaining peaks
for i=1:size(components,1)
    if (i~= significant_pos) 
        if ( i~= max_amp_pos) 
            ordered = [ordered; components(i,1) components(i,2) ];
        end
    end
end    




% % order by freq ascending
% [val,pos]=min(components(:,1));
% ordered = [components(pos,1) components(pos,2)/max_amp ];
% components(pos,1) = 4000;
% for i=2:size(components,1)
% %    disp(['>>Peak:' num2str(ordered(i,2)) ' ' num2str(ordered(i,1)) ' Hz']);
%     [val,pos]=min(components(:,1));
%     ordered = [ordered; components(pos,1) components(pos,2)/max_amp ];
%     components(pos,1) = 4000;
% end

% % order by freq descending
% [val,pos]=max(components(:,1));
% ordered = [components(pos,1) components(pos,2)/max_amp ];
% components(pos,1) = 0;
% for i=2:size(components,1)
% %    disp(['>>Peak:' num2str(ordered(i,2)) ' ' num2str(ordered(i,1)) ' Hz']);
%     [val,pos]=max(components(:,1));
%     ordered = [ordered; components(pos,1) components(pos,2)/max_amp ];
%     components(pos,1) = 0;
% end

end


function freqs = digital_decoding(y, Fs, timming)
% Returns an array of frequencies asssuming the freq changes
% each timming seconds.
% It uses the synchronization function to find the beginning of the
% message

L = length(y);      % Length of signal
slot_duration = timming; % seconds
total_time = L/Fs;
NSlots = floor(total_time/slot_duration);
points_per_slot = floor(L/NSlots);
%disp ( ['Points per slot: ' num2str(points_per_slot) ] );
% NSlots = NSlots -1;
% index = floor(rand * points_per_slot) +1 ;
%index = 1;
index = synchronize(y, Fs, timming/2);
disp( ['Message starts at: ' num2str(index)]);
NSlots = NSlots - ceil(index/points_per_slot);
disp( ['NSlots: ' num2str(NSlots)]);
freqs = [];
for i=1:NSlots
    y_slot = y(index:index + points_per_slot-1); 
    freq = calculateFFTbySlots(y_slot,Fs,timming/10);
    freqs = [ freqs freq];
    %disp( ['Slot freq: ' num2str(freq) ] );
    index = index + points_per_slot;
end


end


function index = synchronize(y, Fs, slot_duration)
% Divides the spectrum into slots, calculates FFT in
% each slot and finds the index when freq changes from
% initial to final.

initial_frequency=600;
final_frequency=800;
precision=20;

L = length(y);      % Length of signal
total_time = L/Fs;
NSlots = floor(total_time/slot_duration);
points_per_slot = floor(L/NSlots);
index = 1;
freq=-1;
freq_1=-1;
for i=1:NSlots
    y_slot = y(index:index + points_per_slot-1); 
    components = calculateFFT(y_slot,Fs,3);
    freq_1 = freq;
    freq = components(1);
    if (freq_1 <0)
        freq_1 = freq;
    end
    if ( abs(freq_1-initial_frequency) < precision) && ( abs(freq-final_frequency) < precision)
        index = index + floor(points_per_slot/2); 
        break;
    end
    index = index + points_per_slot;
end

end
% % % % 
% % % % function components = calculateFFT(y,Fs, NPeaks)
% % % % % Calculates the FFT and returns the main NPeaks
% % % % % [freq_1 ampl_1 freq_2 ...]
% % % % 
% % % % L = length(y);      % Length of signal
% % % % NFFT = 2^nextpow2(L); % Next power of 2 from length of y
% % % % Y = fft(y,NFFT)/L;
% % % % f = Fs/2*linspace(0,1,NFFT/2);
% % % % 
% % % % components = [];
% % % % YY = Y(1:NFFT/2);
% % % % for i=1:NPeaks
% % % %     [val,pos,YY] = obtain_peaks(YY);
% % % %     peak_freq = round(f(pos));
% % % %     components = [components; peak_freq val];
% % % % end
% % % % 
% % % % end
% % % % 
% % % % function [val,pos,YY] = obtain_peaks(Y)
% % % % % Aux functions that obtains a peak and sets the 
% % % % % amplitude = 0 in the peak sorroundings
% % % % npoints = length(Y);
% % % % YY = Y;
% % % % [val,pos]=max(abs(YY));
% % % % %disp(['Peak:' num2str(val) ' ' num2str(peak_freq) ' Hz']);
% % % % peak_amplitude = 10;
% % % % 
% % % % p1 = pos - peak_amplitude;
% % % % p2 = pos + peak_amplitude;
% % % % if p1 < 0
% % % %     p1 = 1;
% % % % end
% % % % if p2 > npoints
% % % %     p2 = npoints;
% % % % end
% % % % for i=p1:p2
% % % %     YY(i) = 0;
% % % % end
% % % % 
% % % % end
% % % % 
function freq = calculateFFTbySlots(y,Fs, slot_duration)
% Splits the signal into slots, calculate the FFT in
% each one and returns the most frequent value (mode)

L = length(y);      % Length of signal
total_time = L/Fs;
NSlots = floor(total_time/slot_duration);
points_per_slot = floor(L/NSlots);
index = 1;
freqs = [];
for i=1:NSlots
    y_slot = y(index:index + points_per_slot-1); 
    components = calculateFFT(y_slot,Fs,3);
    freqs = [ freqs components(1)];
    %disp( ['>>>>freq: ' num2str( components(1) ) ]);
    index = index + points_per_slot;
end
freq = mode(freqs);
end

function index = findFreqStep(y,Fs,slot_duration, stepF)
L = length(y);      % Length of signal
total_time = L/Fs;
NSlots = floor(total_time/slot_duration);
points_per_slot = floor(L/NSlots);
index = 1;
freq_1 = 0;
for i=1:NSlots
    y_slot = y(index:index + points_per_slot-1); 
    components = calculateFFT(y_slot,Fs,1);
    freq = components(1);
    if ( abs(abs(freq-freq_1)-stepF ) < 10  )
        disp( ['Found ' num2str(index) ]);
        break; %step detected
    end
    freq_1 = freq;
    index = index + points_per_slot;
end

% fine tunning
fine_points_per_slot = floor(points_per_slot/10);
for i=1:10
    y_slot = y(index:index + fine_points_per_slot-1); 
    components = calculateFFT(y_slot,Fs,1);
    freq = components(1);
    if ( abs(abs(freq-freq_1)-stepF ) < 10  )
        disp( ['Found refined:' num2str(index) ]);
        break; %step detected
    end
    freq_1 = freq;
    index = index + fine_points_per_slot;
end

while (index > 0)
    index = index - points_per_slot;
end

index = index + points_per_slot;
disp( ['Index:' num2str(index) ]);
end

function freq = decode3XFrequency(f)
synch_freq = 440;
freq_distance = 30;
freq = f;
if ( abs(f-synch_freq)< freq_distance)
    freq = 500;
end
if ( f>1500 && f<2500 )
    freq = freq - 1000;
end
if ( f>2500 && f<3500 )
    freq = freq - 2000;
end

end

function bit = decodeFrecuency2Bit(f)
synch_freq = 520;
zero_f = 700;
one_f = 900;

bit = -1;
freq_distance = 30;
if ( abs(f-synch_freq)< freq_distance)
    bit=-1; % synch bit
end
if ( abs(f-zero_f)< freq_distance)
    bit=0; % synch bit
end
if ( abs(f-one_f)< freq_distance)
    bit=1; % synch bit
end

end


function decodeBinary(y,Fs)

%slot_duration = 0.200 * correction_factor;
L = length(y);      % Length of signal
total_time = L/Fs
%NSlots = floor(total_time/slot_duration);
points_per_slot = 800; % 200ms
NSlots = floor(L/points_per_slot) -1
points_per_bit = L/NSlots;

index = 1;
freqs = [];
bits = [];
bitTimes = [];
while (index + points_per_slot < L)
%    disp ( [num2str(index) ' ' num2str(index + points_per_slot-1)]); 
    y_slot = y(index:index + points_per_slot-1); 
    components = calculateFFT(y_slot,Fs,3);
    freqs = [ freqs components(1)];
    bits = [ bits decodeFrecuency2Bit(components(1))];
    bitTimes = [bitTimes index];
    %disp( ['>>>>freq: ' num2str( components(1) ) ]);
    index = index + points_per_slot;
end
plot(freqs, '-o', 'color', 'b')
grid on

%% decode bits
i = 1;
bNumber = [];
numbers=[];
syncTimes = [];
while (i < length(bits))
    bit = bits(i);
    if (bit < 0)
        syncTimes = [syncTimes bitTimes(i)];
        number = bitArray2number(bNumber);
        %disp( [ 'decoded:' num2str(number)]);
        numbers = [numbers number];
        bNumber = [];
    else
        bNumber = [bNumber bit];
    end
    i = i+1;
end

h = figure();
plot(numbers, '-o', 'color', 'b')
grid on
% hold on
% plot(syncTimes/Fs, numbers, '-o', 'color', 'r')

i=1;
valores=[];
while (i+5 < length(numbers))
    num = numbers(i);
%    num = [syncTimes(i)];
    sTime = syncTimes(i);
    counter = 1;
    while ( abs(syncTimes(i+1)-sTime)< 25000 )
%    while ( counter < 5 )
%        (syncTimes(i+1)-sTime)
        num2 = numbers(i+1);
        num = [num num2];
%        num = [num syncTimes(i+1)];
        i = i+1;
        counter = counter +1;
    end
    for k=length(num):5 
        num = [num -3];
    end
    valores = [valores; num];
end

for k=1:size(valores,1)
    row = valores(k,:);
    values = [];
    for l=1:length(row)
        value = row(l);
        if (value>0)
            values= [values value];
        end
    end
    values
end






% h = figure();
% plot(syncTimes/Fs, '-o', 'color', 'b')
% grid on

end

function number = bitArray2number(bits)
number = 0;
if (length(bits)<1) 
    return;
end
for k=1:length(bits)
    number = bitset(number, k, bits(k));
end
if (length(bits)~=10)
    number = -length(bits)*10;
    return;
end

end

function decode3xF(y, Fs)

slot_duration = 0.2;
synch_freq = 440;
freq_distance = 30;
L = length(y);      % Length of signal
total_time = L/Fs;
NSlots = floor(total_time/slot_duration);
points_per_slot = floor(L/NSlots);
index = 1;
%index = findFreqStep(y, Fs, slot_duration, 1000)
freqs = [];
ff = [];
while (index + points_per_slot < L)
    y_slot = y(index:index + points_per_slot-1); 
    components = calculateFFT(y_slot,Fs,3);
    freqs = [ freqs components(1)];
    ff = [ ff decode3XFrequency(components(1))];
    %disp( ['>>>>freq: ' num2str( components(1) ) ]);
    index = index + points_per_slot;
end
plot(freqs, '-o', 'color', 'b')
hold on
grid on

plot(ff-300, '-o', 'color', 'k')

return

%% Find FIRST synchronization slot
for j=1:10
    f = freqs(j);
    f1 = freqs(j+1);
    if (abs(f-synch_freq) < freq_distance ) && (abs(f1-synch_freq) < freq_distance )
        break;
    end
end

i=j;
while (i+5 < length(freqs))
    j=i;
    used_freqs = [];
    while (j< length(freqs))
        f = freqs(j);
        f1 = freqs(j+1);
        used_freqs = [used_freqs f];
        if (abs(f-synch_freq) < freq_distance ) && (abs(f1-synch_freq) > freq_distance )
            break;
        end
        j = j+1;
    end
    if ( length(used_freqs) >2)
%        disp( ['ERROR Slot :' used_freqs ]);
        used_freqs
    end
    i = j;
    f1 = freqs(i+1);
    f2 = freqs(i+2)-1000;
    f3 = freqs(i+3)-2000;
    disp( ['Slot :' num2str(f1) ' ' num2str(f2) ' ' num2str(f3)]);
    i = i+4;
end

% %
% % while (i+4 < NSlots)
% %     f1 = freqs(i);
% %     f2 = freqs(i+1);
% %     f3 = freqs(i+2);
% %     f4 = freqs(i+3);
% %     f5 = freqs(i+4);
% %     disp( ['Slot :' num2str(f1) ' ' num2str(f2) ' ' num2str(f3) ' ' num2str(f4) ' ' num2str(f5)] );
% %     i=i+5;
% % end
% % 


end

%% message-single-frequency encoding
function decode_single_freq_message(wav_fullname)
[y, Fs, nbits] = wavread(wav_fullname);
total_time = length(y)/Fs;
Fs = 8072; disp ( ['Fixed sampling frequency:' num2str(Fs)]);
L = length(y);

slot_duration = 0.5;
points_per_slot = floor(slot_duration * Fs);
NSlots = floor(total_time/slot_duration);

index = 1;
ff = [];
tt = [];
while (index + points_per_slot < L)
    y_slot = y(index:index + points_per_slot-1);
    components = calculateFFT(y_slot,Fs,1);
    f = components(1);
%    disp( ['# ' num2str(components(1)) ' ' num2str(components(2)) ]);
    ff = [ff f ];
    index = index + points_per_slot;
end
ffs =parse_freq_message(ff);
plot(ffs, '-o')
%messages = parse_message(ffs);


end

function messages = parse_message(freqs)

len = size(freqs,2); 
index = 1;
messages=[];
message = [];
while (index < len )
    start_index = index;
    for i=index:100
        f = freqs(i);
        if ( f == 300)
            start_index = i;
            break;
        end
        if ( f > 500)
            message = [message f];
        end
    end
    messages = [messages; message];
    message = [];
%     messages = [messages; freqs(index:start_index)];
    index = start_index +1;
end

end


function ffs = parse_freq_message(freqs)
start_freq = 3600;
sep_freq = 3700;

len = length(freqs); 
index = 1;
last_value = -1;
last_values = [];
ffs = [];
while (index < len )
    f =freqs(index);
    if (f>3650)
       f = 400;
    end
    if (f>3550)
        f = 300;
    end
    if (f>500)
        f = find_value(freqs, index);
    end

    if (f~= last_value)
        ffs= [ffs f];
        last_value = f;
    end
    index = index +1;

end


end

function value = find_value(freqs, index)
values = [];
len = length(freqs); 
while (index < len )
    f =freqs(index);
    if (f<3550)
        values = [values f];
    else
        index = len;
    end
    index = index +1;
end
value = mean(values);
end

%% message-amplitude encoding
function decode_amplitude_message(wav_fullname)
[y, Fs, nbits] = wavread(wav_fullname);
total_time = length(y)/Fs;
L = length(y);
%Fs = 8072; disp ( ['Fixed sampling frequency:' num2str(Fs)]);

% removing 0.1 seconds at the beginning and the end
npoints = floor(0.1 * Fs);
endpoint = length(y)-npoints;
y = y(8*60*10*npoints:endpoint);

slot_duration = 0.2;
points_per_slot = floor(slot_duration * Fs);
%h = figure();
x = [];
yy = [];
ff = [];
index = 1;
for i=1:180
    index = find_amplitude_step(y, Fs, index, slot_duration);    
    x = [x index];
    yy = [yy 0.01];
    y_slot = y(index:index + points_per_slot-1);
    components = calculateFFT(y_slot,Fs,1);
    f = components(1);
    ff = [ff f];
    index = index + floor(points_per_slot*0.7);
end
plot(abs(y(1:Fs*40)), 'color', 'r');
%plot(abs(y), 'color', 'r');
hold on;grid on;
plot(x, yy, '-o');
% plot(x, '-o');
plot(x, ff/10000, '-o', 'color', 'k');

% % h = figure();
% % index = 1;
% % index = find_amplitude_step(y, Fs, index);
% % %sdisp( ['starting at: ' num2str(index)]);
% % values1 = calculate_amplitude_slots(y, Fs, 1);
% % values = calculate_amplitude_slots(y, Fs, 4625);
% % 
% % plot(values1, 'color', 'r');
% % hold on; grid on;
% % plot(values, '-o', 'color', 'b');


% % slot_duration = 0.2;
% % points_per_slot = floor(slot_duration * Fs);
% % ff = [];
% % amp = [];
% % index =1;
% % while (index + points_per_slot < L)
% %     index = find_amplitude_step(y, Fs, index, slot_duration);
% %     if (index + points_per_slot > L-1)
% %         break
% %     end
% %     y_slot = y(index:index + points_per_slot-1);
% %     components = calculateFFT(y_slot,Fs,1);
% %     f = components(1);
% %     a = calculate_amplitude(y_slot);
% %     amp = [amp a];
% % %    disp( ['# ' num2str(components(1)) ' ' num2str(components(2)) ]);
% %     ff = [ff f ];
% %     index = index + points_per_slot;
% % end
% % plot(ff, '-o')
% % %plot(amp, '-o')
% % %messages = parse_message(ffs);
end

function position = find_amplitude_step(y, Fs, index, slot_duration)
% calculate when signal "steps up" from zero to non-zero

L = length(y);
slot_duration = slot_duration/32;
points_per_slot = floor(slot_duration * Fs);
zero_limit = 0.01;
position = index;
last_amplitude=1;
while (index + points_per_slot < L)
    y_slot = y(index:index + points_per_slot-1);
    amplitude = calculate_amplitude(y_slot);
    if (last_amplitude<zero_limit  && amplitude>zero_limit)
        position = index;
%         h = figure('Name', [num2str(amplitude)]);
%         plot(y_slot, '-o')
        break;
    end
    last_amplitude = amplitude;
    index = index + points_per_slot;
end
end

function amplitude = calculate_amplitude(y_slot)
%amplitude = mean(abs(y_slot));
counter = 0;
amplitude = 0;
zero_limit = 0.1;
L = length(y_slot);
for i=1:L
    if ( abs(y_slot(i)) > zero_limit )
        counter = counter +1;
    end
end
if counter > L/10
    amplitude = 1;
end

% h = figure('Name', [num2str(amplitude)]);
% plot(y_slot, '-o')


end

function values=calculate_amplitude_slots(y, Fs, index, slot_duration)

L = length(y);
%slot_duration = 0.5;
points_per_slot = floor(slot_duration * Fs);

values = [];
indexes = [];
counter = 1;
%while (counter <10)
while (index + points_per_slot < L)
    y_slot = y(index:index + points_per_slot-1);
    amplitude = mean(abs(y_slot));
%     if amplitude>zero_limit/2
%         amplitude = 1;
%     else
%         amplitude = 0;
%     end
    indexes = [indexes index];
    values = [values amplitude];
    index = index + points_per_slot;
    counter = counter +1;
end
end
